<!--
 * @author  dumeng
爱心驿站
-->
<template>
  <div class="serviceposition-index">
    <el-collapse-transition>
      <div v-show="searchshow" class="search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.title"
          placeholder="请输入名称搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <div class="search-btn">
          <el-button
            class="filter-item"
            type="primary"
            @click="handleFilter"
          >搜索</el-button>
          <el-button
            class="filter-item"
            type="primary"
            @click="resettingBtn"
          >重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-show="!searchshow" class="search separate">
        <div class="search-inner">
          <el-row :gutter="15">
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">名称</div>
                <el-input
                  v-model.trim="search.title"
                  style="width: 100%"
                  class="filter-item"
                  placeholder="请输入名称搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">状态</div>
                <check-all-check-box
                  v-model="search.status"
                  :options="dict.ZT"
                  bind-val="dictValue"
                  name="dictName"
                />
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button
            class="filter-item"
            type="primary"
            @click="resettingBtn"
          >重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <!--  <div class="classify-con">
      <div class="classify-con-inner">
        <div class="inner-item">
          <ul :class="{ toggle: classifyactive }">
            <li>分类:</li>
            <li
              :class="{ active: listQuery.type == '' }"
              @click="classifyClick('')"
            >
              全部
            </li>
            <li
              v-for="item in classifyList"
              :key="item.id"
              :class="{ active: listQuery.type == item.id }"
              @click="classifyClick(item.id, item.dictName)"
            >
              {{ item.dictName }}
            </li>
          </ul>
          <span @click="classifyToggle()">
            <i v-if="classifyactive" class="el-icon-caret-bottom" />
            <i v-if="!classifyactive" class="el-icon-caret-top" />
          </span>
        </div>
      </div>
    </div> -->
    <div class="btn-container" style="margin-top: 10px;">
      <div class="btn-container-title">
        <span>{{ $route.meta.name }}</span>
      </div>
      <div class="btn-container-btns">
        <el-button

          class="filter-item"
          style="margin-left: 10px"
          @click="handleCreate"
        >新建</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleUpload">
          批量导入
        </el-button>
        <el-button

          class="filter-item"
          style="margin-left: 10px"
          @click="handleDeletes"
        >批量删除</el-button>
      </div>
    </div>
    <div class="table">
      <my-table
        :list="list"
        :filter-column="filtercolumn"
        tag="axyz"
        operationwidth="80"
        :list-loading="listLoading"
        @handleSelectionChange="handleSelectionChange"
      >
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          class-name="small-padding fixed-width"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleUpdateState(scope.row)"
            >{{
              scope.row.status === "ZT01" ? "禁用" : "启用"
            }}</el-button>
            <template v-if="scope.row.status === 'ZT02'">
              <el-button
                type="text"
                size="mini"
                @click="handleUpdate(scope.row)"
              >编辑</el-button>
              <el-button
                type="text"
                size="mini"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
            <!-- <el-button type="text" size="mini" @click="handleView(scope.row)">预览</el-button> -->
          </template>
        </el-table-column>
      </my-table>
    </div>
    <div class="btn-pagion fix">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <preview
      :dialog-status="isShowPreview"
      :title="viewobj.name"
      :content="viewobj.content"
      @onclose="closePreview()"
    />

    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :title="'批量导入'"
      :visible.sync="uploadVisible"
      center
      width="450px"
    >
      <el-upload
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在导入请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        accept=".xls, .xlsx"
        class="upload-model"
        drag
        multiple
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击导入</em>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="uploadVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="uploadSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  queryPage,
  dels,
  del,
  send,
  cancle,
  getDictByCode
} from '@/views/staffserve/axyz/api/index'
import Pagination from '@/components/Pagination'
import permission from '@/directive/permission/index.js'
import MyTable from '@/components/Table'
import CheckAllCheckBox from '@/components/CheckAllCheckBox/index.vue'
import Preview from '@/components/Preview'
import {
  getToken
} from '@/utils/auth'
import elDragDialog from '@/directive/el-drag-dialog'
import { importSign } from '@/utils/fileImportOrExportSign'
export default {
  name: 'ServicepositionIndex',
  components: { Pagination, MyTable, CheckAllCheckBox, Preview },
  directives: { permission, elDragDialog },
  data() {
    return {
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        title: '',
        type: ''
      },
      searchshow: true,
      search: {
        title: '',
        status: []
      },
      list: [],
      total: 0,
      classifyactive: false,
      multipleSelection: [],
      dict: {
        ZT: []
      },
      isShowPreview: false,
      viewobj: {},
      classifyList: [],
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/servicePositional/import',
      uploadHeaders: {
        'ttsxyhcs': getToken(),
        'ttsxbid': 1
      },
      uploadVisible: false,
      loadingUpload: false
    }
  },
  created() {
    if (this.$route.query && this.$route.query.t) {
      this.listQuery.type = this.$route.query.t
    }
    this.getList()
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  methods: {
    uploadSubmit() {
      if (this.$refs['upload'].uploadFiles.length === 0) {
        this.$message.error('请上传文件')
      } else {
        this.$set(this, 'uploadHeaders', importSign(this.uploadHeaders, {}))
        this.$refs.upload.submit()
        this.loadingUpload = true
      }
    },
    handleUpload() {
      this.uploadVisible = true
      this.$nextTick(() => {
        this.$refs.upload.clearFiles()
      })
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.getList()
        this.uploadVisible = false
      } else {
        this.$message.error(data.msg || '批量导入失败')
        this.$refs.upload.clearFiles()
        this.getList()
      }
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
      this.$refs.upload.clearFiles()
    },
    closePreview() {
      this.isShowPreview = false
    },

    filtercolumn(scope, item) {
      if (item === 'phone') {
        // return CryptoJS.$aesJieM(scope.row[item])
        return scope.row[item]
      } else {
        return scope.row[item]
      }
    },

    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    resettingBtn() {
      this.listQuery.page = 1
      this.listQuery.title = ''
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleCreate() {
      this.$router.push({ path: this.$filterPath('manage'), query: { type: 'c', t: this.listQuery.type }})
    },

    handleUpdate(row) {
      this.$router.push({ path: this.$filterPath('manage'), query: { type: 'u', i: row.id, t: this.listQuery.type }})
    },

    handleView(row) {
      const { actionType, content } = row
      this.$set(this, 'viewobj', { actionType, content })
      this.isShowPreview = true
    },

    /** *
     * 点击分类查询列表
     */
    classifyClick(id) {
      this.listQuery.type = id
      this.getList()
    },

    classifyToggle() {
      this.classifyactive = !this.classifyactive
    },

    /**
     * 状态修改
     */
    handleUpdateState(row) {
      let msg = ''
      if (row.status === 'ZT01') {
        msg = '禁用'
      } else {
        msg = '启用'
      }
      this.$confirm('确定' + msg + '此爱心驿站吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          if (row.status === 'ZT01') {
            cancle(row.id).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: msg + '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          } else {
            send(row.id).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: msg + '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          }
        })
      }).catch()
    },

    /**
     * 删除操作
     */
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          del(row.id).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    /**
     * 批量删除
     */
    handleDeletes() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.$confirm('此操作将永久删除所选数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.multipleSelection.forEach(item => {
            arr.push(item.id)
          })
          var ids = arr.join(',')
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            dels(ids).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        }).catch()
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },

    getList(obj) {
      const query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        type: this.listQuery.type
      }
      if (!this.searchshow) {
        query['name'] = this.search.title
        query['status'] = this.search.status && this.search.status.length > 0 && this.search.status.length !== this.dict.ZT.length ? this.search.status.join(',') : ''
      } else {
        query['name'] = this.listQuery.title
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(query).then(res => {
          this.listLoading = false
          this.list = res.data.data.rows || []
          this.total = res.data.data.total || 0
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    }
  }
}
</script>
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
.serviceposition-index {
  padding: 10px 20px 10px 10px;
	.el-upload-dragger{
		width: 408px;
	}
  .search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: "";
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: "";
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .classify-con {
    display: flex;
    background-color: #fff;
    margin-top: 10px;
    margin-bottom: 10px;
    .classify-con-inner {
      flex: 1;
      .inner-item {
        position: relative;
        ul {
          padding: 5px 20px;
          margin: 0;
          box-shadow: 0 5px 10px rgba(254, 90, 97, 0.05);
          max-height: 50px;
          transition: all 1s ease;
          overflow: hidden;
          li {
            list-style-type: none;
            display: inline-block;
            padding: 6px 12px;
            font-size: 14px;
            font-serviceposition: PingFangSC-Medium;
            font-weight: 500;
            color: rgba(51, 51, 51, 1);
            margin: 5px;
            cursor: pointer;
            &:first-child {
              margin: 0;
              padding: 0;
              color: #a6a6a6;
            }
            &.active {
              @include font-color($mainColor);
              background: #eaf7ff;
              border-radius: 17px;
            }
          }
          &.toggle {
            max-height: 300px;
          }
        }
        span {
          position: absolute;
          right: 10px;
          top: 12px;
          @include font-color($mainColor);
          cursor: pointer;
          font-size: 20px;
        }
      }
    }
    .classify-con-btn {
      position: relative;
      width: 120px;
      .el-button {
        position: absolute;
        top: 50%;
        margin-top: -18px;
        left: 50%;
        margin-left: -45px;
      }
    }
  }
  .btn-container {
    display: flex;
    height: 36px;
    line-height: 36px;
    margin-bottom: 10px;
    .btn-container-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      font-serviceposition: PingFangSC-Medium;
      color: rgba(51, 51, 51, 1);
    }
  }
}
</style>
